package com.example.future;

import com.example.util.CommonUtils;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CommonUtils.printThreadLog("开始");

        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 读取新闻
        Future<String> newsFuture = executor.submit(() -> {
            String news = CommonUtils.readFile("news.txt");
            CommonUtils.printThreadLog("原news=\n" + news);
            return news;
        });
        // 读取敏感词
        Future<String[]> filterWordsFuture = executor.submit(() -> {
            String filterWords = CommonUtils.readFile("filter_words.txt");
            CommonUtils.printThreadLog("filterWords=" + filterWords);
            if (filterWords.isEmpty()) {
                return new String[0];
            }
            return filterWords.split(",");
        });
        // 替换敏感词
        Future<String> replaceFuture = executor.submit(() -> {
            CommonUtils.printThreadLog("替换敏感词Future，开始");
            String news = newsFuture.get();
            String[] filterWords = filterWordsFuture.get();
            for (String filterWord : filterWords) {
                news = news.replaceAll(filterWord, "***");
            }
            CommonUtils.printThreadLog("替换敏感词Future，结束");
            return news;
        });
        // 输出最终文本
        String news = replaceFuture.get();
        CommonUtils.printThreadLog("替换后的news=\n" + news);

        executor.shutdown();
        CommonUtils.printThreadLog("结束");
    }

}
